<?php
/**
 * 【司机相关】
 * Created by PhpStorm.
 * User: 孙凯
 * Date: 2018-06-04
 * Time: 19:00
 */

namespace App\Http\Controllers;


use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Support\Facades\DB;

class ChauffeurController extends Controller
{
    /**
     * 【司机请假列表】
     * @Author sk
     * @DateTime 2018-06-05
     * @param Request $request
     * @return array
     */
    public function index(Request $request)
    {
        /* $keys = $request->all();
         $handle = DB::table('driver');
         foreach ($keys as $key => $val) {
             $keys[$key] && $handle->where($key, 'like', '%' . $val . '%');
         }
         $datas = $handle->get()->toarray();
         dd($datas);*/

        $dat = $request->all();
        $keys = array_splice($dat, 1);
        $handle = DB::table('chauffeur_leave')
            ->join('roles', 'chauffeur_leave.approval_id', '=', 'roles.id')
            ->join('driver', 'chauffeur_leave.chauffeur_id', '=', 'driver.id')//差司机
            ->join('convoy', 'driver.convoy_id', '=', 'convoy.id')//车队
            ->join('branch', 'convoy.branch_id', '=', 'branch.id')//机构;
            ->orderBy('chauffeur_leave.time', 'desc');//日志表
        foreach ($keys as $key => $val) {
            $keys[$key] && $handle->where($key, 'like', '%' . $val . '%');
        }
        $datas = $handle->get();
        $datas = json_decode(json_encode($datas), true);
        // dd($datas);
        foreach ($datas as $k => &$v) {
            $v['start_time'] = date('Y-m-d H:i:s', $v['start_time']);
            $v['end_time'] = date('Y-m-d H:i:s', $v['end_time']);
            $v['newtime'] = $v['start_time'] . '/' . $v['end_time'];
        }
        //  $splz=
        $dataform = json_decode(json_encode($datas), true);
        if ($dataform) {
            return response(['msg' => $dataform, 'code' => 1000, 'message' => '司机请假数据返回成功！'], 200);
        } else {
            return response(['msg' => '', 'code' => 1011, 'message' => '司机请假数据查询失败！'], 400);
        }

    }

    /**
     * 【司机请假详情show】
     * @Author sk
     * @DateTime 2018-06-05
     * @param chauffeur_id int 司机id
     * @param Request $request
     * @return array
     */
    public function show(Request $request)
    {
        $array = $request->all();
        if (empty($array['chauffeur_id'])) {
            return '参数不完整';
        }
        try {
            $id = $array['chauffeur_id'];
            //查询司机的信息
            $info = Db::table('driver')->where('id', $id)->first();
            // $info = get_object_vars($info);
            //查询车队的信息
            //查询的字段
            $convoydata = [
                'name',//车队名称
                'branch_id',//机构的id
                'captain_id',//队长的id
            ];

            $convoy = Db::table('convoy')->where('id', $info->convoy_id)->select($convoydata)->first();
            //$convoy = get_object_vars($convoy);

            //查询队长姓名
            $captainname = Db::table('driver')->where('id', $convoy->captain_id)->select('driver_name')->first();
            $captainname = get_object_vars($captainname);

            //查询机构的信息
            $branch = Db::table('branch')->where('id', $convoy->branch_id)->select('company_name')->first();
            $branch = get_object_vars($branch);

            //查询司机的请假申请内容
            $obj = DB::table('chauffeur_leave')->where('id', $id)->first();
            //dd($obj);
            //审核日志查询
            //$number = $array['number'];
            $appol = DB::table('approval_log')->where('number', $obj->number)->get();
            if (empty($appol)){
                return '无数据了';
            }
            $a = json_decode(json_encode($appol), true);

            /*  foreach ($a as $k => &$v) {
                  if ($v['results'] == '1') {
                      $pass['pass'] = '审核通过';
                  } elseif ($v['results'] == '2') {
                      $pass['pass'] = '审核为通过';
                  } elseif ($v['results'] == '3') {
                      $pass['pass'] = '审核打回';
                  }else{
                      $pass['pass'] = '完成';
                  }
              }
              dd($pass);*/
            foreach ($a as $k => &$v) {
                //dd($v);
                $v['time'] = date('Y-m-d H:i:s', $v['time']);//审核时间
                $cc = $v['role_id'];
                $dd = $v['lead'];
                $tt = $v['time'];
                $data['opinion'] = $v['opinion'];//审批意见
                $data['results'] = $v['results'];//审核结果
                $data['lead'] = $v['lead'];//审核人姓名
                $data['circuit_number'] = $v['circuit_number'];//审批流程号
            }
            $data['role_id'] = $cc;
            $data['lead'] = $dd;
            $info = get_object_vars($info);

            foreach ($a as $k => &$val) {
                // $info= get_object_vars($info);
                switch ($val['results']) {
                    case 0:
                        $pass[$k]['title'] = '创建';
                        $pass[$k]['name'] = $info['driver_name'];
                        $pass[$k]['time'] = $tt;
                        break;
                    case 1:
                        $pass[$k]['title'] = '拒绝';
                        $pass[$k]['name'] = $dd;
                        $pass[$k]['time'] = $tt;
                        break;
                    case 2:
                        $pass[$k]['title'] = '打回';
                        $pass[$k]['name'] = $dd;
                        $pass[$k]['time'] = $tt;
                        break;
                    case 3:
                        $pass[$k]['title'] = '完成';
                        $pass[$k]['time'] = $tt;
                        break;
                }
            }
            /*$data['opinion'] = $appol['opinion'];//审批意见
            $data['results'] = $appol['results'];//审核结果
            $data['lead'] = $appol['lead'];//审核人姓名
            $data['circuit_number'] = $appol['circuit_number'];//审批流程号
            $data['time'] = $appol['time'];//审核时间*/
            $obj = get_object_vars($obj);
            $convoy = get_object_vars($convoy);
            $data['ftime'] = date('Y-m-d H:i:s', $obj['time']);//请假发起时间
            $data['from'] = $obj['from'];//申请来源:1:司机,2:APP
            $data['reason'] = $obj['reason'];//请假原因
            $data['start_time'] = $obj['start_time'];//请假开始时间
            $data['end_time'] = $obj['end_time'];//请假结束时间

            $data['name'] = $convoy['name'];//车队名称
            $data['driver_name'] = $captainname['driver_name'];//队长名称
            $data['company_name'] = $branch['company_name'];//机构名称
            //  $data = json_decode(json_encode(array($data)),true);
            return $appol ? response(['data' => $a, 'a' => $data, 'pass' => $pass, 'code' => 1000, 'message' => '信息返回成功！'], 200) : response(['data' => '', 'code' => 1011, 'message' => '信息返回失败！'], 400);
        } catch (JWTException $e) {
            return response(['msg' => '', 'code' => 1011, 'message' => '非法的token']);
        }

    }

    /**
     * 【司机请假审批】
     * @type 1：同意请假，2拒绝请假
     * @id 司机id
     * @Author sk
     * @DateTime 2018-06-05
     * @param Request $request
     * @return array
     */
    public function save(Request $request)
    {
        $data = $request->all();
        $id = $data['chauffeur_id'];
        $status = Db:: table('driver')->where('id', $id)->first();
        $status = get_object_vars($status);
        if (isset($status['attendant']) && $status['attendant'] == 5) {
            return response(['msg' => $status, 'code' => 1000, 'message' => '请假已经审批成功！'], 200);
        }
        try {
            if ($data['type'] == 1) {
                $leave = Db:: table('driver')->where('id', $id)->update(['attendant' => 5]);
                $msg = json_encode($leave);
                $sg = Db:: table('approval_log')->where('number', $data['number'])
                    ->update([
                        'role_id' => $data['role_id'],
                        'lead' => $data['lead'],
                        'time' => time(),
                        'results' => $data['type'],
                        'opinion' => $data['opinion'],
                        'circuit_number' => date('his') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT),
                        'number' => date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 10), 1))), 0, 6),
                    ]);
                $dataform = json_decode(json_encode($sg && $status), true);
                return $msg ? response(['msg' => $msg, 'code' => 1000, 'message' => '请假同意成功！'], 200) : response(['msg' => '', 'code' => 1011, 'message' => '同意请假操作失败！'], 400);
            } elseif ($data['type'] == 2) {
                //type==2 为拒绝请假
                $status = Db::table('chauffeur_leave')->where('chauffeur_id', $id)->update(['status' => 1]);
                $sg = Db:: table('approval_log')->where('number', $data['number'])
                    ->update([
                        'role_id' => $data['role_id'],
                        'lead' => $data['lead'],
                        'time' => time(),
                        'results' => $data['type'],
                        'opinion' => $data['opinion'],
                        'circuit_number' => date('his') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT),
                        'number' => date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 10), 1))), 0, 6),
                    ]);
                $dataform = json_decode(json_encode($sg && $status), true);
                $dataform = json_encode($status);
                if ($dataform) {
                    return response(['msg' => $dataform, 'code' => 1000, 'message' => '请假拒绝成功！'], 200);
                } else {
                    return response(['msg' => '', 'code' => 1011, 'message' => '拒绝请假操作失败！'], 400);
                }
            } else {
                return response(['msg' => '', 'code' => 1011, 'message' => '传递参数错误操作失败！'], 400);
            }
        } catch (JWTException $e) {
            return response(['msg' => '', 'code' => 1011, 'message' => '非法的验证']);
        }
    }
}
